<template>
  <div class="center">
    <!-- <n-card :bordered="false">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        :submitButtonText="'查询'"
        :show-feedback="false"
        :resetButtonText="'重置'"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card> -->
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        :pagination="false"
      >
        <template #tableTitle>
          <n-space>
            <n-button size="small" @click="addTable"> 新建部门 </n-button>
            <n-button size="small"> 添加用户 </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <Model
      :showModal="showModal"
      :FormData="FormData"
      :formValue="formValue"
      :title="title"
      :rules="rules"
      @ModelClick="ModelClick"
      @close="close"
    >
    </Model>
    <ModelBox
      :ModelBox="ModelBox"
      :center="center"
      :title="title"
      @determine="determine"
      @close="close"
    ></ModelBox>
  </div>
</template>

<script lang="ts">
import { h, defineComponent, reactive, ref, onMounted } from 'vue';
import { useMessage,NTag } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Form/index';
import { fetchDepartmentDetailsList,fetchDepartmentList,fetchIndustryList,addDepartment,deleteDepartment,updateDepartment } from '@/api/Department/index';
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { Model } from '@/components/Model';
import { ModelBox } from '@/components/ModelBox';
export default defineComponent({
  name:'organizationManagement',
  components: {
    BasicTable,
    BasicForm,
    PlusOutlined,
    Model,
    ModelBox,
  },
  setup() {
    const columns = [
      {
        type: 'selection',
        fixed: 'left'
      },
      {
        title: '分组',
        key: 'departmentName',
      },
      {
        title: '人数',
        key: 'personCount',
        render (row) {
          if(row.personCount){
            return row.personCount
          }else {
            return '-'
          }
        }
      },
      // {
      //   title: '区域id',
      //   key: 'districtCode',
      //   width:200,
      //   render (row) {
      //     if(row.districtCode){
      //       return row.districtCode
      //     }else {
      //       return '-'
      //     }
      //   }
      // },
      // {
      //   title: '所属行业',
      //   width:200,
      //   key: 'industryList',
      //   render (row) {
      //     if(row.industryList.length == 0){
      //       return '-'
      //     } else {
      //       const tags = row.industryList.map((tagKey) => {
      //         return h(
      //           NTag,
      //           {
      //             style: {
      //               marginRight: '6px'
      //             },
      //             type: 'primary'
      //           },
      //           {
      //             default: () => tagKey.industryName ? tagKey.industryName : '-'
      //           }
      //         )
      //       })
      //       return tags
      //     }
      //   }
      // },
    ];
    const actionRef = ref();
    const router = useRouter();
    const formRef: any = ref(null);
    const center = ref(null);
    const message = useMessage();
    const title = ref(null);
    const showModal = ref(false);
    const ModelBox = ref(false);
    const formBtnLoading = ref(false);
    const formValue = ref({});
    const departmentData = ref([])
    const ModeldepartmentData = ref([]);
    const FormData = ref([
      {
        label: '组织名称',
        type: 'n-input',
        enName: 'departmentName',
        clearable: true,
        size: 'small',
        show:true,
        placeholder: '请输入组织名称',
        span: 24,
      },
      {
        label: '上级组织',
        type: 'n-tree-select',
        enName: 'parentId',
        leafonly:false,
        clearable: true,
        size: 'small',
        show:true,
        placeholder: '请选择上级组织',
        span: 24,
        options: [],
      },
      {
        label: '区域id',
        type: 'n-input',
        enName: 'districtCode',
        clearable: true,
        size: 'small',
        show:true,
        placeholder: '请输入区域id',
        span: 24,
      },
      {
        label: '行业',
        type: 'n-select',
        enName: 'EchoIndustryList',
        multiple: true,
        clearable: true,
        size: 'small',
        show:true,
        placeholder: '请选择行业',
        span: 24,
        options: [],
      },
    ]);
    const formParams = ref({
      name: '',
      address: '',
      date: null,
    });
    const params = ref({size : 10, page:1});
    const Obj = ref({})
    const rules = ref({
        departmentName: {
          required: true,
          message: '请输入组织名称',
          trigger: ['input', 'blur'],
        },
        districtCode: {
          required: true,
          message: '请输入区域id',
          trigger: ['blur', 'change'],
        },
        parentId: {
          required: true,
          message: '请选择上级组织',
          trigger: ['blur', 'change'],
        },
        EchoIndustryList: {
          type:'array',
          required: true,
          message: '请选择行业',
          trigger: ['blur', 'change'],
        },
    })
    const actionColumn = reactive({
      width: 150,
      title: '操作',
      key: 'action',
      fixed: 'right',
      render(record) {
        return h(TableAction as any, {
          text: true,
          actions: [
            {
              label: '查看',
              type: 'primary',
              text: true,
              onClick: see.bind(null, record),
            },
            {
              label: '编辑',
              type: 'primary',
              text: true,
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              type: 'primary',
              text: true,
              onClick: handleDelete.bind(null, record),
            },
          ],
          select: (key) => {
            message.info(`您点击了，${key} 按钮`);
          },
        });
      },
    });
    const schemas = [
      {
        field: 'isEnable',
        component: 'NSelect',
        label: '所属部门',
        size: 'small',
        componentProps: {
          placeholder: '请选择部门',
          options: [
            {
              label: '部门111',
              value: 1,
            },
            {
              label: '部门222',
              value: 0,
            },
          ],
        },
      },
    ];
    const [register, {}] = useForm({
      gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
      labelWidth: 80,
      schemas,
    });

    const data = ref({list:[]});
    const ArrayData = ref([])
    const loadDataTable = async (res) => {
      data.value.list = [];
      ArrayData.value =  await fetchDepartmentDetailsList();
      ArrayData.value.map((res) => {
        if(res.parentId == 0){
          data.value.list.push(res)
        }
      });
      let request = await recursion(data.value.list);
      return request.value
    };

    const recursion = async (data) => {
      try {
        // const r =  await fetchDepartmentDetailsList();
        for(var i = 0; i < data.length; i ++){
            for (var j = 0; j < ArrayData.value.length; j++) {
              if(ArrayData.value[j].parentId == data[i].id){
                if (data[i].hasOwnProperty('children')) {
                  data[i].children.push(ArrayData.value[j])
                } else {
                  data[i].children = []
                  data[i].children.push(ArrayData.value[j])
                }
              }
            }
          if(data[i].children){
            // children若不为空数组，则继续递归调用本方法
            recursion(data[i].children);
          }
        }
      } catch(e){
        console.log(e)
      }
      const Obj = ref({list:[]})
      Obj.value.list = data
      return Obj;
    }

    const handleEdit = (record: Recordable) => {
      title.value = '编辑部门';
      FormData.value.map((res) => {
        res.disabled = false;
      })
      record.EchoIndustryList = record.industryList.map((res) => {
        return res.id
      });
      record.districtCode = record.districtCode.toString()
      industry();
      formValue.value = record
      showModal.value = true;
    };

    const handleDelete = (record: Recordable) => {
      Obj.value = record;
      ModelBox.value = true;
      title.value = '删除';
      center.value = '是否确定要删除?';
    };

    const see = async (record: Recordable) => {
      title.value = '查看部门';
      FormData.value.map((res) => {
        res.disabled = true;
      });
      record.EchoIndustryList = record.industryList.map((res) => {
        return res.id
      });
      record.districtCode = record.districtCode.toString()
      industry();
      formValue.value = record
      showModal.value = true;
    };

    //删除确定按钮
    const determine = async(e) => {
      ModelBox.value = e;
      if(title.value == '删除') {
        await deleteDepartment(Obj.value.id);
        actionRef.value.reload();
      }
    }
    //查询
    const handleSubmit = (row) => {
      console.log(row.trim)
      try {
        params.value = { ...params.value, ...row };
        actionRef.value.reload();
      } catch (e) {
        console.error(e)
      }
    };

    //新增
    const addTable = async () => {
      title.value = '新建部门';
      industry();
      FormData.value.map((res) => {
        res.disabled = false;
      })
      formValue.value = {}
      showModal.value = true;
    };

    //模态框确定
    const ModelClick = async (e) => {
      if(title.value == '新建部门'){
        let CopyObj = {...formValue.value};
        CopyObj.industryList = CopyObj.EchoIndustryList
        delete CopyObj.EchoIndustryList
        await addDepartment(CopyObj);
        actionRef.value.reload();
      }else if(title.value == '编辑部门'){
        let CopyObj = {...formValue.value};
        CopyObj.industryList = CopyObj.EchoIndustryList
        delete CopyObj.EchoIndustryList
        await updateDepartment(CopyObj);
        actionRef.value.reload();
      }
      showModal.value = e;
      ModelBox.value = e;
    };
    //模态框关闭
    const close = (e) => {
      showModal.value = e;
      ModelBox.value = e;
    };

    //获取行业 && 获取部门
    const industry = async () => {
      departmentData.value = [];
      let data = await fetchIndustryList();
      ModeldepartmentData.value = await fetchDepartmentList();
      //部门数据处理
      ModeldepartmentData.value.map((res) => {
        if(res.parentId == '0'){
          departmentData.value.push({
            label:res.departmentName,
            key:res.id,
            id:res.id
          })
        }
      });
      let request = await DepartmentRecursion(departmentData.value);
      //行业数据处理
      let dataArray = data.map((res) => {
        return {
          label:res.industryName,
          value:res.id
        }
      })
      FormData.value.map((res) => {
        if(res.enName == 'EchoIndustryList'){
          res.options = dataArray
        }else if(res.enName == 'parentId'){
          res.options = request
        }
      })
    }
    //部门递归
    const DepartmentRecursion = async (data) => {
      try {
        for(var i = 0; i < data.length; i ++){
            for (var j = 0; j < ModeldepartmentData.value.length; j++) {
              if(ModeldepartmentData.value[j].parentId == data[i].id){
                if (data[i].hasOwnProperty('children')) {
                  data[i].children.push({
                    label:ModeldepartmentData.value[j].departmentName,
                    key:ModeldepartmentData.value[j].id,
                    id:ModeldepartmentData.value[j].id
                  })
                } else {
                  data[i].children = []
                  data[i].children.push({
                    label:ModeldepartmentData.value[j].departmentName,
                    key:ModeldepartmentData.value[j].id,
                    id:ModeldepartmentData.value[j].id
                  })
                }
              }
            }
          if(data[i].children){
            // children若不为空数组，则继续递归调用本方法
            DepartmentRecursion(data[i].children);
          }
        }
      } catch(e){
        console.log(e)
      }
      return data
    }


    return {
      rules,
      data,
      departmentData,
      schemas,
      router,
      formRef,
      Obj,
      ModeldepartmentData,
      ArrayData,
      message,
      actionRef,
      showModal,
      ModelBox,
      formBtnLoading,
      formParams,
      params,
      actionColumn,
      register,
      loadDataTable,
      handleEdit,
      handleDelete,
      see,
      columns,
      handleSubmit,
      determine,
      ModelClick,
      close,
      addTable,
      title,
      FormData,
      formValue,
      center,
    };
  },
});
</script>

<style lang="less" scoped>
.center :deep .n-card {
  margin: 0 0 20px 0;
}
</style>
